package com.guc.coroutines.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
import android.util.Log
import java.lang.StringBuilder

/**
 * Created by guc on 2022/2/17.
 * Description：广播中执行耗时程序
 * 您不应从广播接收器启动长时间运行的后台线程。onReceive() 完成后，系统可以随时终止进程来回收内存，在此过程中，也会终止进程中运行的派生线程。要避免这种情况，您应该调用 goAsync()（如果您希望在后台线程中多花一点时间来处理广播）或者使用 JobScheduler 从接收器调度 JobService，这样系统就会知道该进程将继续活跃地工作
 */
private const val TAG = "MyBroadcastReceiver"

class MyBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent) {
        val pendingResult = goAsync() //
        val asyncTask = Task(pendingResult, intent)
        asyncTask.execute()
    }

    private class Task(private val pendingResult: PendingResult, private val intent: Intent) :
        AsyncTask<String, Int, String>() {
        override fun doInBackground(vararg params: String?): String {
            val sb = StringBuilder()
            sb.append("Action:${intent.action}\n")
            sb.append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
            return sb.toString().also { log ->
                Log.e(TAG, log)
            }
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            pendingResult.finish()
        }
    }
}